package com.jintu.portal.controller;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.pojo.bean.Filter;
import com.jintu.portal.pojo.bean.IsRegister;
import com.jintu.portal.pojo.bean.QLBuilder;
import com.jintu.portal.pojo.dto.IndexInfoDto;
import com.jintu.portal.pojo.dto.PullCodeDto;
import com.jintu.portal.pojo.entity.ExtendCode;
import com.jintu.portal.pojo.entity.UserCodeRel;
import com.jintu.portal.pojo.submit.ResultInfo;
import com.jintu.portal.repository.mysql.dao.ExtendCodeDao;
import com.jintu.portal.repository.mysql.dao.UserCodeRelDao;
import com.jintu.portal.service.IndexService;
import com.jintu.portal.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liyou on 2017/9/29.
 */
@Slf4j
@Controller
public class IndexController extends BaseController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private UserCodeRelDao userCodeRelDao;

    @Autowired
    private ExtendCodeDao extendCodeDao;


    /**
     * 首页信息查询
     * @return
     * @throws Exception
     */
    @RequestMapping("index")
    @ResponseBody
    public ResultInfo index(HttpServletRequest request) throws Exception {
        IndexInfoDto indexInfoDto = indexService.indexInfo(request);
        return returnSuccess(indexInfoDto);
    }

//    /**
//     * 同步clientId
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("syncClientId")
//    @ResponseBody
//    public ResultInfo syncClientId(@RequestBody JSONObject jsonObject) throws Exception {
//        String clientId = jsonObject.getString("clientId");
//        if(StringUtil.isBlank(clientId)) {
//            throw new ServiceException("缺失必要参数");
//        }
//        userSerivce.syncClientId(UserUtil.tobCurrentUser().getUserId(), clientId);
//        return returnSuccess();
//    }

    /**
     * 动态二维码获取
     * @return
     * @throws Exception
     */
    @RequestMapping("index/dimCode")
    @ResponseBody
    public ResultInfo dimCode(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        PullCodeDto dto = new PullCodeDto();
        String token = request.getParameter("token");
        Long userId = UserUtil.tobCurrentUser1(token).getUserId();
//        Long userId = 111111l;
        Integer area_id = jsonObject.getInteger("areaId");
        Integer upstreamId = jsonObject.getInteger("upstreamId");

        QLBuilder ql = new QLBuilder();
        ql.and(Filter.eq("type", upstreamId));
        ql.and(Filter.eq("userId", userId));
        if(area_id != null){
            ql.and(Filter.eq("areaId", area_id));
        }
        UserCodeRel rel = userCodeRelDao.findOneByJpql(ql);
        if(rel == null){
            //未关联二维码
            List<Object> paramList = new ArrayList<Object>();
            String sql = "";
            if(area_id != null){
                sql="select a.* from extend_code a left join user_code_rel b \n" +
                        "on a.id = b.code_id where a.type = :upstreamId and a.area_id = :area_id and b.id is null limit 1;";
                paramList.add(upstreamId);
                paramList.add(area_id);
            }else{
                sql="select a.* from extend_code a left join user_code_rel b \n" +
                        "on a.id = b.code_id where a.type = :upstreamId and b.id is null limit 1;";
                paramList.add(upstreamId);
            }

            List<ExtendCode> employeeList = extendCodeDao.findManyBySql(sql,ExtendCode.class,paramList.toArray());
            if(employeeList != null && employeeList.size() > 0){
                ExtendCode extendCode = employeeList.get(0);
                if(extendCode !=null){
                    dto.setCodeUrl(extendCode.getLink());
                    //分配完二维码后建立分配关系
                    UserCodeRel codeRel = new UserCodeRel();
                    codeRel.setUserId(userId);
                    codeRel.setType(upstreamId);
                    codeRel.setCodeId(extendCode.getId());
                    if(area_id != null){
                        codeRel.setAreaId(area_id);
                    }
                    codeRel.setCreateTime(System.currentTimeMillis());
                    userCodeRelDao.insert(codeRel);
                }
            }else{
                ResultInfo result = new ResultInfo();
                result.setStatus(500);
                result.setMessage("二维码已分配完，请联系官方客服！");
                log.info("二维码已分配完毕:" + upstreamId);
                return result;
            }

        }else{
            //已关联二维码
            ExtendCode extendCode = extendCodeDao.get(rel.getCodeId());
            if(extendCode != null){
                dto.setCodeUrl(extendCode.getLink());
            }
        }

        return returnSuccess(dto);
    }

}
